import axios from "axios";
import Vue from "vue";
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
    state:{
        list:[],
        inputValue:'',
        viewKey:'all'
    },
    getters:{
        //统计未完成的任务条数
        getReduce(state){
            return state.list.filter(item => item.done=== false).length
        },
        //获取对应的view数据项
        infoList(state){
            if(state.viewKey == 'all'){
                return state.list
            }
            if(state.viewKey == 'unDone'){
                return state.list.filter(item => item.done == false)
            }
            if(state.viewKey == 'done'){
                return state.list.filter(item => item.done == true)
            }
        }

    },
    mutations:{
        //初始化列表数据
        initList(state,list){
            state.list = list
        },
        //设置文本框内容
        setInputValue(state,newValue){
            state.inputValue = newValue
        },
        //向列表添加待办事项
        addItem(state){
            const obj = {
                id: state.list.length?state.list.length:0,
                info:state.inputValue,
                done:false
            }
            state.list.push(obj)
            state.inputValue = ''
        },
        //根据id删除数据
        removeItem(state,id){
            const i =  state.list.findIndex(x => x.id === id)
            if(i !== -1){
                state.list.splice(i,1)
            }   
        },
        //根据id改变数据项的status
        changeStatus(state,obj){
            const i = state.list.findIndex(x => x.id === obj.id)
            if(i !== -1){
                state.list[i].done = obj.status
            }     
        },
        //清除已完成的任务
        cleanDone(state){
            state.list =  state.list.filter(item => item.done === false)
        },
        //修改页面展示的数据
        changeViewKey(state,type){
            state.viewKey =  type
        }
        
    },
    actions:{
        getList(context){
           axios.get('/list.json').then(({data})=>{
                context.commit('initList',data)
            })
        }
        
    }
})
export default store